package city.spring.modules.medicine.service.impl;

import city.spring.modules.medicine.entity.MedicineEntity;
import city.spring.modules.medicine.entity.MedicinereceiptEntity;
import city.spring.modules.medicine.repository.MedicinereceiptRepository;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.medicine.service.MedicinereceiptService;
import city.spring.modules.medicine.vo.MedicinereceiptVO;
import city.spring.modules.personnel.entity.EmployeeEntity;
import city.spring.modules.personnel.repository.EmployeeRepository;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.UserService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.List;

/**
 * Service：药品领用申请
 *
 * @author 谢金婷
 * @date 2020-06-27 11:27:59
 */
@CacheConfig(cacheNames = {MedicinereceiptServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class MedicinereceiptServiceImpl extends ServiceImpl<MedicinereceiptRepository, MedicinereceiptEntity> implements MedicinereceiptService {

    private static final Logger logger = LoggerFactory.getLogger(MedicinereceiptServiceImpl.class);
    private final MedicineService medicineService;
    private final UserService userService;
    private final EmployeeRepository employeeRepository;
    private final MedicinereceiptRepository medicinereceiptRepository;
    private final EmployeeService employeeService;

    public MedicinereceiptServiceImpl(MedicineService medicineService, UserService userService, EmployeeRepository employeeRepository, MedicinereceiptRepository medicinereceiptRepository, EmployeeService employeeService) {
        this.medicineService = medicineService;
        this.userService = userService;
        this.employeeRepository = employeeRepository;
        this.medicinereceiptRepository = medicinereceiptRepository;
        this.employeeService = employeeService;
    }

    @Override
    public void saveMedicinereceipt(MedicinereceiptEntity entity, @NonNull Principal user) {


        //设置申请领取人员为当前登录用户
        UserEntity userEntity = userService.getUserByIdOrAccount(user.getName());
        entity.setReceipter(userEntity.getId());
        //设置所属部门
//        //1.根据用户id获取信息
        EmployeeEntity employeeEntity = employeeService.getById(userEntity.getId());
        System.out.println(employeeEntity);
//        //2.设置部门
        entity.setDepartment(employeeEntity.getOrgId());
        System.out.println("entity.getDepartment()" + entity.getDepartment());
        // 设置审核人申请用户主管
        EmployeeEntity employeeDuty = employeeRepository.getDuties(employeeEntity.getOrgId());
        System.out.println("employeeDuty:employeeDuty====" + employeeDuty);
        entity.setReviewer(employeeDuty.getId());
        //审核状态为待审核
        entity.setApprovalStatus(1);
        // 出库状态 未出库
        entity.setDeliveryStatus(2);
        //计量单位
        //1.获取物资信息
        MedicineEntity medicineEntity = medicineService.getById(entity.getMedicineId());
        System.out.println(medicineEntity);
        //2.设置计量单位
        entity.setUnitmeasurement(medicineEntity.getUnit());

        /**
         * 库存提示：计算目前库存减去待出库后的库存
         */
        BigDecimal optionalQuantity = medicinereceiptRepository.getOptionalQuantity(medicineEntity.getName(), medicineEntity.getCategory(), medicineEntity.getSpecifications(), medicineEntity.getType(), medicineEntity.getUnit(), medicineEntity.getDosageunit()) == null ? BigDecimal.ZERO : medicinereceiptRepository.getOptionalQuantity(medicineEntity.getName(), medicineEntity.getCategory(), medicineEntity.getSpecifications(), medicineEntity.getType(), medicineEntity.getUnit(), medicineEntity.getDosageunit());

        // 领用数量小于最大可领用数量则保存， 否则提示
        if (entity.getQuantity().compareTo(optionalQuantity) < 1) {
            save(entity);
        } else {
            throw new RuntimeException("领用数量大于最大可领数量。当前最大可领数量: " + optionalQuantity + entity.getUnitmeasurement() + "。  保存信息失败");
        }

//        if (!save(entity)) {
//            throw new RuntimeException("保存信息失败");
//        }
    }

    @Override
    public void updateMedicinereceipt(MedicinereceiptEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        //设置审核状态为待审核
        entity.setApprovalStatus(1);

        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteMedicinereceipt(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteMedicinereceipt(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }

    @Override
    public MedicinereceiptEntity getMedicinereceiptById(String id) {
        return medicinereceiptRepository.getMedicinereceiptById(id);
    }

    @Override
    public IPage<MedicinereceiptEntity> getMedicinereceiptPass(Pageable pageable) {
        IPage<MedicinereceiptEntity> page = MyBatisUtils.toPage(pageable);
        return medicinereceiptRepository.getMedicinereceiptPass(page, lambdaQuery().getWrapper());
    }

    @Override
    public IPage<MedicinereceiptEntity> getMedicinereceiptNoPass(Pageable pageable) {

        IPage<MedicinereceiptEntity> page = MyBatisUtils.toPage(pageable);
        return medicinereceiptRepository.getMedicinereceiptNoPass(page, lambdaQuery().getWrapper());
    }

    @Override
    public IPage<MedicinereceiptVO> listPage(Page<? extends MedicinereceiptEntity> page, Wrapper<? extends MedicinereceiptEntity> wrapper) {
        return baseMapper.listPage(page, wrapper);

    }

    @Override
    public IPage<MedicinereceiptVO> approvalListPage(Page<? extends MedicinereceiptEntity> page, Wrapper<? extends MedicinereceiptEntity> wrapper) {
        return baseMapper.approvalListPage(page, wrapper);
    }

    @Override
    public IPage<MedicinereceiptVO> deliveryListPage(Page<? extends MedicinereceiptEntity> page, Wrapper<? extends MedicinereceiptEntity> wrapper) {
        return baseMapper.deliveryListPage(page, wrapper);
    }

    /**
     * 统计最大可领用数量
     * 现有库存-待出库数量（领用待审核数量）
     *
     * @param type
     * @param name
     * @param category
     * @param specifications
     * @param unit
     * @param dosageunit
     * @return
     */
    @Override
    public BigDecimal getOptionalQuantity(String name, String category, String specifications, String type, String unit, String dosageunit) {
        return medicinereceiptRepository.getOptionalQuantity(name, category, specifications, type, unit, dosageunit);
    }

}